package com.dmall.sort.algorithm;

/**
 * 最基本的归并排序算法
 * @author xiao1.wang
 * @date 2021/10/7 20:26
 */
@SuppressWarnings("all")
public class MergeSort implements Sort {
    @Override
    public void sort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        mergeSort(arr, 0, arr.length - 1);
    }

    /**
     * 对数组arr指定范围[left, right]进行归并排序
     * @param arr 待排序数组
     * @param left 区间起始索引
     * @param right 区间终止索引
     */
    private void mergeSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int pivot = left + ((right - left) >>> 1);
        mergeSort(arr, left, pivot);
        mergeSort(arr, pivot + 1, right);
        if (arr[pivot] > arr[pivot + 1]) {
            merge(arr, left, pivot, right);
        }
    }

    /**
     * 将数组的两个区间（[left, pivot] and [pivot + 1, right]）进行合并操作
     * @param arr 待合并的数组
     * @param left 左区间起始索引
     * @param pivot 左区间终止索引
     * @param right 右区间终止索引
     */
    private void merge(int[] arr, int left, int pivot, int right) {
        int[] temp = new int[right - left + 1];
        int indexL = left;
        int indexR = pivot + 1;
        int index = 0;
        while (indexL <= pivot && indexR <= right) {
            if (arr[indexL] <= arr[indexR]) {
                temp[index ++] = arr[indexL ++];
            } else {
                temp[index ++] = arr[indexR ++];
            }
        }
        while (indexL <= pivot) {
            temp[index ++] = arr[indexL ++];
        }
        while (indexR <= right) {
            temp[index ++] = arr[indexR ++];
        }
        // 复制到原数组中
        System.arraycopy(temp, 0, arr, left, index);
    }

    @Override
    public String getName() {
        return "归并排序";
    }

    public static void main(String[] args) {
        int[] arr = {6, 9, 4, 7, 2, 8, 3, 1, 10, 5};
        Sort.printArr(arr);
        Sort sort = new MergeSort();
        sort.sort(arr);
        Sort.printArr(arr);
    }
}
